import { Component, OnInit, OnDestroy } from '@angular/core';
import { ChatService } from './chat.service';

@Component({
  selector: 'test-chat',
  template:  `<nb-chat title="Test Chat" size="large" satus="primary">
                <nb-chat-message *ngFor="let msg of messages"
                   [type]="msg.type"
                   [message]="msg.text"
                   [reply]="msg.reply"
                   [sender]="msg.user.name"
                   [avatar]="msg.user.avatar"
                   [date]="msg.date"
                   [files]="msg.files"
                   [quote]="msg.quote">
                </nb-chat-message>
                <nb-chat-form (send)="sendMessage($event)" [dropFiles]="true"></nb-chat-form>
              </nb-chat>`,
  providers: [ChatService]
})
export class TestChatComponent implements OnInit, OnDestroy {

  messages: any[] = [];
  connection: any;

  constructor(private chatService: ChatService) {
  }

  sendMessage(event: any) {
    const files = !event.files ? [] : event.files.map((file) => {
      return {
        url: file.src,
        type: file.type,
        icon: 'nb-compose'
      };
    });

    const msgObj = {
      text: event.message,
      date: new Date(),
      reply: true,
      type: files.length ? 'file' : 'text',
      files: files,
      user: {
        name: 'chen',
        avatar: 'https://i.gifer.com/no.gif'
      }
    };

    this.chatService.sendMessage(msgObj);
  }

  ngOnInit() {
    this.connection = this.chatService.getMessages()
      .subscribe(message => {
        this.messages.push(message);
      });
  }

  ngOnDestroy() {
    this.connection.unsubscribe();
  }
}
